package com.reliable.service.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.reliable.api.dto.template.TemplateAnalysisRecordDTO;
import com.reliable.api.param.template.ReliableTemplateAnalysisTaskParam;
import com.reliable.api.param.template.TemplateAnalysisRecordPageParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.common.core.page.TableDataInfo;
import com.reliable.service.domain.ReliableAnalysisTemplate;
import com.reliable.service.domain.ReliableTemplateAnalysisTask;
import com.reliable.service.service.ChatMessageService;
import com.reliable.service.service.IReliableAnalysisTemplateService;
import com.reliable.service.service.IReliableTemplateAnalysisTaskService;
import com.reliable.service.utils.IdEncryptUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板关联的分析任务Controller
 */
@RestController
@RequestMapping("/reliable/template/analysis/task")
@Api(tags = "模板关联的分析任务管理")
@Validated
public class ReliableTemplateAnalysisTaskController {

    @Autowired
    private IReliableTemplateAnalysisTaskService reliableTemplateAnalysisTaskService;

    @Autowired
    private IReliableAnalysisTemplateService templateService;


    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 新增模板关联的分析任务
     */
    /**
     * 新增模板关联的分析任务
     */
    @PostMapping("/create-task")
    @ApiOperation("为模板创建新的分析任务（返回 taskId）")
    public AjaxResult createAnalysisTask(@RequestBody ReliableTemplateAnalysisTaskParam param) {


        Long templateId = IdEncryptUtils.decrypt(param.getTemplateId());
        // 1. 检查模板是否存在且启用
        ReliableAnalysisTemplate template = templateService.getById(templateId);
        if (template == null || template.getIsActive()!=1 || template.getDelFlag() == 1) {
            return AjaxResult.error("模板不存在或已禁用");
        }

        // 2. 创建 analysis task（此时 upload_record 还不存在，可设为 null 或稍后 update）
        ReliableTemplateAnalysisTask task = new ReliableTemplateAnalysisTask();
        task.setTemplateId(templateId);
        reliableTemplateAnalysisTaskService.save(task);

        // 3. 返回 taskId 给前端，前端上传时携带此 ID
        Map<String, Object> result = new HashMap<>();

        result.put("taskId", IdEncryptUtils.encrypt(task.getId()));
        return AjaxResult.success(result);
    }
    /**
     * 分页查询模板分析记录
     */
    @ApiOperation("分页查询模板分析记录")
    @PostMapping("/page")
    public TableDataInfo page(@RequestBody TemplateAnalysisRecordPageParam param) {
        param.setTemId(IdEncryptUtils.decrypt(param.getTemplateId()));
        IPage<TemplateAnalysisRecordDTO> page = reliableTemplateAnalysisTaskService.pageTemplateAnalysisRecords(param);
        for (TemplateAnalysisRecordDTO record : page.getRecords()) {
            Long count = chatMessageService.countDistinctSessionsByTaskId(record.getId());
            record.setTotalSessions(count.intValue());
            if (record.getAnalyzedSessions()!=null && record.getAnalyzedSessions()!=0)
            {
                record.setBlacklistSessions(count.intValue()-record.getAnalyzedSessions());
            }

            record.setBusinessId(IdEncryptUtils.encrypt(record.getId()));
            record.setId(null);

        }

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }
}